#include <stdio.h>
#include <stdlib.h>

//二进制:写入数据块
int main1()
{
    FILE *fp = fopen("G:/Desktop/b.txt", "wb");
    if (!fp)
    {
        return -1;
    }
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    fwrite(arr, sizeof(int), 10, fp);
    //准备写入文件数据的地址
    fclose(fp);
}

//二进制:读取数据块
int main2()
{
    FILE *fp = fopen("G:/Desktop/b.txt", "rb");
    if (!fp)
    {
        return -1;
    }
    int arr[10] = {0};
    fread(arr, sizeof(int), 10, fp);
    //存放读取出来数据的内存空间
    for (int i = 0; i < 10; i++)
    {
        printf("%d\n", arr[i]);
    }
    fclose(fp);
}

typedef struct student
{
    char name[21];
    int age;
} stu;

//二进制读写结构体
int main3()
{
    stu ss[3] = {{"黄某航", 9},
                 {"马某羊", 3},
                 {"大法师", 30}};
    FILE *fp = fopen("G:/Desktop/b.txt", "wb");
    if (!fp)
        return -1;
    fwrite(ss, sizeof(stu), 3, fp);
    fclose(fp);
}

int main()
{
    stu *ss = (stu *)malloc(sizeof(stu) * 3);
    FILE *fp = fopen("G:/Desktop/b.txt", "rb");
    fread(ss, sizeof(stu), 3, fp);
    for (int i = 0; i < 3; i++)
    {
        printf("姓名:%s", ss[i].name);
        printf("年龄:%d", ss[i].age);
        printf("\n");
    }
    fclose(fp);
    free(ss);
}